package com.zb.kc.controller;


import com.zb.kc.client.VodClient;
import com.zb.kc.commonutils.R;
import com.zb.kc.entity.EduVideo;
import com.zb.kc.entity.form.VideoInfoForm;
import com.zb.kc.service.IEduVideoService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author wanggen
 * @since 2020-04-10
 */
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {

    @Autowired
    private IEduVideoService videoService;

    @ApiParam(value = "根据小节id获取小节")
    @GetMapping("{id}")
    public R getVideoById(@PathVariable("id") String id) {
        VideoInfoForm video = videoService.getVideoFormById(id);
        return R.ok().data("item", video);
    }

    @ApiOperation(value = "添加小节")
    @PostMapping
    public R addVideo(@RequestBody VideoInfoForm video) {
        videoService.saveVideoInfo(video);
        return R.ok();
    }

    @Autowired
    private VodClient vodClient;

    @ApiOperation(value = "删除小节")
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable("id") String id) {
        EduVideo eduVideo = videoService.getById(id);
        // 判断小节里是否有视频
        if (!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            // 根据视频id远程调用删除阿里云上的视频
            R res = vodClient.removeAlyVideo(eduVideo.getVideoSourceId());
            if (res.getCode() != 20000) {
                return R.err().message(res.getMsg());
            }
        }
        boolean result = videoService.removeById(id);
        if (result) {
            return R.ok();
        } else {
            return R.err().message("删除课时失败");
        }
    }

    @ApiOperation(value = "修改小节")
    @PutMapping
    public R updateVideo(@RequestBody VideoInfoForm video) {
        videoService.updateVideo(video);
        return R.ok();
    }

}
